package com.htx.zqs.blesmartmask;

import android.app.Application;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.util.DisplayMetrics;

import com.clj.fastble.BleManager;
import com.clj.fastble.BuildConfig;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.Courses;
import com.htx.zqs.blesmartmask.broadcastreceiver.NetworkChange;
import com.htx.zqs.blesmartmask.db.DaoManager;
import com.htx.zqs.blesmartmask.ui.callback.MeBluetoothGattCallback;
import com.htx.zqs.blesmartmask.utils.ActivityManager;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.BleUtils;
import com.htx.zqs.blesmartmask.utils.Constants;
import com.htx.zqs.blesmartmask.utils.FileLogUtils;
import com.htx.zqs.blesmartmask.utils.LogcatHelper;
import com.htx.zqs.blesmartmask.utils.MySpUtils;
import com.htx.zqs.blesmartmask.utils.ScreenManager;
import com.htx.zqs.blesmartmask.utils.Utils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.tencent.bugly.Bugly;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.ArrayList;
import java.util.TimeZone;

import timber.log.Timber;


/**
 * Created by zhao on 2018/5/12.
 */

public class MyApplication extends Application {
    public static MyApplication sApplication;
    public static int bluetoothState = 0;
    public static int runningIndex = -1;
    public static boolean isConnected = false;
    public static boolean isCourseExist = false;
    public static Context appContext;
    public static Courses selectCourse;
    public static Courses runningCourse;
    public static BluetoothGatt bluetoothGatt;
    public static MeBluetoothGattCallback meBluetoothGattCallback;
    public static int currentDevicePosition = -1;
    public static Integer limitCount = 0;
    public static boolean isTestWater = false;
    public static ArrayList<Courses> courses;
    public static Integer limitSeconds = 0;
    public static int state = 10000;
    public static String lauguage;
    private static ActivityManager sActivityManager;

    @Override
    public void onCreate() {
        super.onCreate();
        sApplication = this;
        appContext = getApplicationContext();
        //适配
        // resetDensity();
        ScreenManager.setDensity(this);
        lauguage = BlEUtile.getLanguage();
        UMConfigure.init(this, "5b2c6db2f43e48380a000045", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, null);
        MobclickAgent.setCatchUncaughtExceptions(false);
        //监听网络改变广播注册
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(NetworkChange.getInstance(), filter);

        //init log
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        } else {
            Timber.plant(new CrashReportingTree());
        }

        //init ble
        initBle();
        MySpUtils.getInstance(this, "my_sp");
        DaoManager.getInstance(this).setDebug(true);


        Bugly.init(this, "a70be5bcc9", false);

//        initBaseUrl
        Contants.BASE_URL = Utils.isChinaZones() ? Contants.URL_CHINA : Contants.URL_FOREIGN;
        X5Init();

        FileLogUtils.init(this);
    }

    private void X5Init() {
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    private void initBaseUrl() {
        if (Utils.isChinaZones()) {

        }
    }

    public static MyApplication getApplication() {
        return sApplication;
    }

    public static synchronized ActivityManager getActivityManager() {
        if (sActivityManager == null) {
            sActivityManager = ActivityManager.getInstance();
        }
        return sActivityManager;
    }

    private static class CrashReportingTree extends Timber.Tree {
        @Override
        protected void log(int priority, String tag, String message, Throwable t) {

        }
    }

    //初始化配置
    private void initBle() {
        BleManager.getInstance().init(this);
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)
                .setSplitWriteNum(20)
                .setConnectOverTime(10000)
                .setOperateTimeout(10000);
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceName(true, BleUtils.BLE_NAME)
                .setScanTimeOut(0)//无限扫描
                .setAutoConnect(false)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterReceiver(NetworkChange.getInstance());
    }

    public static String getCourseFromIndex(int index) {
        if (courses == null || courses.size() == 0) {
            return courses.get(0).getName();
        } else {
            for (int i = 0; i < courses.size(); i++) {
                if (courses.get(i).getId() == index) {
                    return courses.get(i).getName();
                }
            }
        }
        return courses.get(0).getName();
    }

    private void resetDensity() {
        //绘制页面时参照的设计图尺寸
        final float DESIGN_WIDTH = 1080f;
        final float DESIGN_HEIGHT = 1920f;
        final float DESTGN_INCH = 5.0f;
        //大屏调节因子，范围0~1，因屏幕同比例放大视图显示非常傻大憨，用于调节感官度
        final float BIG_SCREEN_FACTOR = 0.2f;
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //确定放大缩小比率
        float rate = Math.min(dm.widthPixels, dm.heightPixels) / Math.min(DESIGN_WIDTH, DESIGN_HEIGHT);
        //确定参照屏幕密度
        float referenceDensity = (float) Math.sqrt(DESIGN_WIDTH * DESIGN_WIDTH + DESIGN_HEIGHT * DESIGN_HEIGHT) / DESTGN_INCH / 160;
        //确定最终屏幕密度
        float relativeDensity = referenceDensity * rate;
        if (relativeDensity > dm.density) {
            relativeDensity = relativeDensity - (relativeDensity - dm.density) * BIG_SCREEN_FACTOR;
        }
        dm.density = relativeDensity;
    }

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                return new MaterialHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));
                // 指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }
}
